/* 
 * Fichier javascript pour le bloc image
 * dans Fo : ajout annonnce
 */

	 var toListesImagesRestants = new Array() ;
	 var zImagePrincipal		= "" ;
     $(function(){
        
		var item = '';
		var delSrc = '';
		var noImage = $('#noImage').val();
		if(document.getElementById('accordion'))  $("#accordion").accordion({autoHeight: false,collapsible: true});
		if(document.getElementById('accordion2')) $("#accordion2").accordion({autoHeight: false,collapsible: true});
       
       
        function countImage () {
            nbr = 0;
            if ($.trim($('.infiniteCarousel ul').html()) == "") return 0;
            $('.infiniteCarousel ul li').each(function () {
                cl = $(this).attr('class');
                if(cl!="cloned" && cl!="empty cloned" && cl!="empty" ){
					nbr++;
				}

            });

            return nbr+1;
        }
        
        //chargement dynamique des modeles en fonctions de la marque choisie
        $("#ess_iMarqueId").change(function(){
            var zUrlModel1 = $('#urlLoadModele').val();
            if ($(this).val() != ""){

                $.getJSON(zUrlModel1,{iMarqueId: $(this).val()}, function(result){
                zoptions = '';
                size = result.length;

                for (i = 0; i < size; i++) {
                    zoptions += '<option value="' + result[i].modele_id + '">' + result[i].modele_libelle + '</option>';
                }
                $("#ess_iModelId").html(zoptions);
                });
            }else {
                $("#ess_iModelId").html("<option value=''>Modeles</option>");
            }
        });
        
       

        //commentaires limité à 90 carctères
        $(".comment").keyup(function(){
            var content = $(this).val();
            if(content.length <= 90){
                    $("#cptr").val(90 - content.length);
            } else {
                $("#cptr").val(0);
                $(this).val(content.substring(0, 90));
            }
        });

            $('#status_fic').hide();
            $('#status_supp').hide();
           //mecanisme file upload fichier principal
			var path		= $('#path_min').val();
			var btnUpload	= $('#upload'); 
			var delSrc = $('#delImage').val();
			new AjaxUpload(btnUpload, 
			{  
				action: j_basepath + 'uploads.php',  
				//Name of the file input box  
				name: 'uploadfile',  
				onSubmit: function(file, ext){  
					if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){  
						// check for valid file extension  
						alert('Only JPG, PNG or GIF files are allowed');  
						return false;  
					}
					$('#status_fic p').html("Chargement de : " + file);
					$('#status_fic').show();
				},  
				onComplete: function(file, response){

					//On completion clear the status  
					$('#status_fic').hide();

					//Add uploaded file to list
					if(response.search('success') != -1 ){  
						
							$('#fic_princ').val(file);
							$('#thumb').attr('src',path + file);
							zImagePrincipal		= file ;
							array_push(toListesImagesRestants,file) ;
							var cptr			= 1;
							var photo_annonce	= $('#photo-annonce').val();
							var html			= '<ul id="ao_carousel" class="jcarousel-skin-tango">';
								html+= '<li><a hre="'+path + file+'">';
								html+= '<img src="'+path + file+'"  class="photo_princ" title="' + file+'"  width="84" height="84"/></a>';
								html+= '<img src="'+delSrc+'"  onclick="supprimerImage(\''+file+'\');" class="deleteImage" title="Supprimer cette image" />';
								html+= '</li>';	
							
								
								html += '</ul>';
								
								//On append l'image choisi 
								$(".div_ao_caroussel").css("display","block") ;
								$('.div_ao_caroussel').html(html);
								$('#ao_carousel').jcarousel({
									scroll:1,
									wrap: 'first',
									visible:3
								});
								
								$('#ap_img').attr('src',path + file);
								$(".showPP").attr('href',path+file);
								$(".showPP").attr('key',path+file);
								$(".showPP img").attr('alt',file);
								initCarousel();
								
					}
				  }  
			   });
                
             //mecanisme file upload fichier supplémentaire
            var btnUpload=$('#upload_supp');  
		    var tailleMaximal		=  0 ;
			var delSrc = $('#delImage').val();
            new AjaxUpload(btnUpload, 
			{  
                action: j_basepath + 'uploads.php',  
                //Name of the file input box  
                name: 'uploadfile',  
                onSubmit: function(file, ext){
                    if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){  
                        // check for valid file extension  
                        alert('Only JPG, PNG or GIF files are allowed');  
                        return false;  
                    }  
                    $('#status_supp p').html("Chargement de : " + file);
                    $('#status_supp').show();  
                },  
                onComplete: function(file, response){
					var zUrlImage			= $('#urlCheckImage').val();
					
					$.getJSON(zUrlImage,{file: file}, function(result)
					{
						 //debut ajax
							tailleMaximal	= parseFloat(result);
							var tailleImage = parseFloat( filesize(path+file) ) ;
							if(tailleImage>tailleMaximal) {
								
								alert("Votre image est plus grande") ;
								$(".loading").attr("src","") ;
								return false ;
							}else{

								//On completion clear the status  
								$('#status_supp').hide();  

								//Add uploaded file to list
								if(response.search('success') != -1 )
								{
															
									//On teste s'il a entrer plus de 10 images
									if (getCountImage() >9){
										alert('Vous ne pouvez plus ajouter des images supplémentaires. Merci');

									}else{
										$('.div_ao_caroussel').append("");

										$('#fic_supp').val(file);
										$('#thumb_supp').attr('src',path + file);
										array_push(toListesImagesRestants,file) ;
										
										var photo_annonce	= $('#photo-annonce').val();
										var html			= '<ul id="ao_carousel" class="jcarousel-skin-tango">';
										var forPop			= "";
											for (var iIndex=0;iIndex<toListesImagesRestants.length;iIndex++)
											{
												var zFile = toListesImagesRestants[iIndex] ;
												if(zImagePrincipal!=zFile)
												{	
													html += '<li>';
													html += '<a href="'+path + zFile+'" rel="prettyPhoto[pp_gal]">';
													html += '<img src="'+path + zFile+'" title="' + zFile+'"  width="84" height="84"/>';
													html += '</a>';
													html += '<img src="'+delSrc+'"  onclick="supprimerImage(\''+zFile+'\');" class="deleteImage" title="Supprimer cette image" />';
													html += '</li>';
												}
												
												
											}
											html += '</ul>';
											
											//On append les imagesx
											$(".div_ao_caroussel").css("display","block") ;
											$('.div_ao_caroussel').html(html);
											$('#ao_carousel').jcarousel({
												scroll:1,
												wrap: 'first',
												visible:3
											});
											photo_annonce += (photo_annonce == '') ? file : ',' + file;
											$('#photo-annonce').val(photo_annonce);
											$('#ap_img').attr('src',path + file);
											$(".showPP").attr('href',path+file);
											$(".showPP img").attr('alt',file);
											initCarousel();
									}
								}
							}
						  //fin ajax ()
						});
                }  
            });
			
			$(".showPP").click(function(){
				supprimerImage("");
				var thisSrc = $(this).attr('href') ;

				$('#ao_carousel li a').each(function(){
					if (thisSrc == $(this).attr('href'))
					{
						$(this).trigger('click');
					}
				});
				return false ;
			});
            
            
        });


 //Les fonctions necessires
function searchInArray(val,tab){
	var len = tab.length;
	for(i=0;i<len;i++){
		if(tab[i] == val) {
			return true; 
		}
	}return false;
}
        
         
function hideOrShowIfEmpty(ul,div){
   var contenu = $.trim($(ul).html());
	if (contenu == ""){
		$(div).hide();
	} else {
		$(div).show();
	}
}

function filesize (url) 
{

	  var req = this.window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
	  if (!req) {
		throw new Error('XMLHttpRequest not supported');
	  }

	  req.open('HEAD', url, false);
	  req.send(null);

	  if (!req.getResponseHeader) {
		try {
		  throw new Error('No getResponseHeader!');
		} catch (e) {
		  return false;
		}
	  } else if (!req.getResponseHeader('Content-Length')) {
		try {
		  throw new Error('No Content-Length!');
		} catch (e2) {
		  return false;
		}
	  } else {
		return req.getResponseHeader('Content-Length');
	  }
 }

 function getCountImage () {
 
	nbr = 0;
	$('#ao_carousel li img[class=deleteImage]').each(function () {
			nbr=nbr+1;
	});

	return nbr+1;
 
 } 

 function initPP(){
	$(".forPopUp:first a[rel^='prettyPhoto']").prettyPhoto({
		social_tools: ''
	}); 
 }
// html
 function supprimerImage(zImageName){
	var delSrc				= $('#delImage').val();
	var zPath				= $('#path_min').val();
	toListesImagesRestants	= unset(zImageName,toListesImagesRestants) ;
	var html = '<ul id="ao_carousel" class="jcarousel-skin-tango">';
	var zDernierImage		= "" ;									
	for (var iIndex=0;iIndex<toListesImagesRestants.length;iIndex++)
	{
		var zFile = toListesImagesRestants[iIndex] ;
		html+= '<li>';
		html+= '<a href="'+zPath + zFile+'" rel="prettyPhoto[pp_gal]">';
		html+= '<img src="'+zPath + zFile+'" title="' + zFile+'"  width="84" height="84"/>';
		html+= '</a>';
		html+= '<img src="'+delSrc+'"  onclick="supprimerImage(\''+zFile+'\');" class="deleteImage" title="Supprimer cette image"/>';
		html+= '</li>';

		zDernierImage	= zFile ;
	}
	
	html+= '</ul>';
	$(".div_ao_caroussel *").remove() ;
	
	$('.div_ao_caroussel').html(html);
	$('#ao_carousel').jcarousel({
		scroll:1,
		wrap: 'first',
		visible:3
	});
	
	$("#ap_img").attr("src",zPath+zDernierImage) ;
	$("#thumb_supp").attr("src",zPath+zDernierImage) ;
	$("#fic_supp").val(zDernierImage) ;
	$(".showPP").attr('href',zPath+zDernierImage);
	$(".showPP img").attr('alt',zDernierImage);
	initCarousel();
	//s'il na pas d'image no_image.jpg
	var noImage = $('#noImage').val();
	if(toListesImagesRestants.length==0){
		$("#ap_img").attr("src",noImage) ;
		$("#thumb_supp").attr("src",noImage) ;
		$(".div_ao_caroussel *").remove() ;
	}
 }

 function array_push (inputArr) {
  var i = 0,
    pr = '',
    argv = arguments,
    argc = argv.length,
    allDigits = /^\d$/,
    size = 0,
    highestIdx = 0,
    len = 0;
  if (inputArr.hasOwnProperty('length')) {
    for (i = 1; i < argc; i++) {
      inputArr[inputArr.length] = argv[i];
    }
    return inputArr.length;
  }

  // Associative (object)
  for (pr in inputArr) {
    if (inputArr.hasOwnProperty(pr)) {
      ++len;
      if (pr.search(allDigits) !== -1) {
        size = parseInt(pr, 10);
        highestIdx = size > highestIdx ? size : highestIdx;
      }
    }
  }
  for (i = 1; i < argc; i++) {
    inputArr[++highestIdx] = argv[i];
  }
  return len + i - 1;
}

function in_array (needle, haystack, argStrict) {
  var key = '',
    strict = !! argStrict;

  if (strict) {
    for (key in haystack) {
      if (haystack[key] === needle) {
        return true;
      }
    }
  } else {
    for (key in haystack) {
      if (haystack[key] == needle) {
        return true;
      }
    }
  }

  return false;
}

function str_replace (search, replace, subject, count) {
  var i = 0,
    j = 0,
    temp = '',
    repl = '',
    sl = 0,
    fl = 0,
    f = [].concat(search),
    r = [].concat(replace),
    s = subject,
    ra = Object.prototype.toString.call(r) === '[object Array]',
    sa = Object.prototype.toString.call(s) === '[object Array]';
  s = [].concat(s);
  if (count) {
    this.window[count] = 0;
  }

  for (i = 0, sl = s.length; i < sl; i++) {
    if (s[i] === '') {
      continue;
    }
    for (j = 0, fl = f.length; j < fl; j++) {
      temp = s[i] + '';
      repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
      s[i] = (temp).split(f[j]).join(repl);
      if (count && s[i] !== temp) {
        this.window[count] += (temp.length - s[i].length) / f[j].length;
      }
    }
  }
  return sa ? s : s[0];
}

function initCarousel(){	
	$("a[rel^='prettyPhoto']").prettyPhoto({
			social_tools: '' 
	});
		
}

function unset(oElement,oMap){
	
	var oMapReturn = new Array() ;
	if(oElement){
		for (iIndex = 0; iIndex<oMap.length;iIndex++)
		{
			var oCurentElement = oMap[iIndex] ;
			
			if(oCurentElement!==oElement){
				
				array_push(oMapReturn,oCurentElement) ;
			}
		}
		return oMapReturn ;
		
	}else{
		return oMap ;
	}	

}